package com.eorchis.module.deptassignedinfo.ui.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.commond.converter.IQueryCommondAttributeConverter;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.deptassignedinfo.domain.DepAssigneInfoQueryBean;
import com.eorchis.module.deptassignedinfo.domain.DeptAssigneInfoExport;
import com.eorchis.module.deptassignedinfo.domain.DeptAssigneInfoSheet;
import com.eorchis.module.deptassignedinfo.domain.DeptAssignedInfo;
import com.eorchis.module.deptassignedinfo.domain.DeptAssignedInfoBean;
import com.eorchis.module.deptassignedinfo.domain.ExportDeptAssigneInfoBean;
import com.eorchis.module.deptassignedinfo.service.IDeptAssignedInfoService;
import com.eorchis.module.deptassignedinfo.ui.commond.DeptAssignedInfoQueryCommond;
import com.eorchis.module.deptassignedinfo.ui.commond.DeptAssignedInfoValidCommond;
import com.eorchis.module.preauthorizationregistration.domain.PreSqSyUserBean;
import com.eorchis.module.signupdept.domain.SignupDept;
import com.eorchis.module.trainingclass.domain.TrainingClass;
import com.eorchis.utils.excelutil.ExcelIO;
import com.eorchis.utils.excelutil.ExcelIOFactory;
import com.eorchis.utils.excelutil.export.bo.Sheet;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: DeptAssignedInfoController<br>
 * Description: 单位年度参学名额表管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Administrator
 * @createDate 2014-12-29
 * @version $Revision$
 */
@Controller("deptAssignedInfoController")
@RequestMapping(value = DeptAssignedInfoController.MODULE_PATH)
public class DeptAssignedInfoController extends AbstractBaseController<DeptAssignedInfoValidCommond,DeptAssignedInfoQueryCommond> {
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/deptassignedinfo";
	// 单位年度参学名额表接口
	@Resource(name = "com.eorchis.module.deptassignedinfo.service.impl.DeptAssignedInfoServiceImpl")
	private IDeptAssignedInfoService deptAssignedInfoService;
	@Autowired
	@Qualifier("attributeConverter")
	private ArrayList<IQueryCommondAttributeConverter> attributeConverter;
	@Override
	public IBaseService getService() {
		return deptAssignedInfoService;
	}

	@Override
	public String getModulePath() {
		return MODULE_PATH;
	}
	/**
	 * 分配参学名额的列表
	 * @param querycommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2014-12-29
	 */
	@RequestMapping(value = "/findDeptAssignedInfoList")
	public String findDeptAssignedInfoList(
			@ModelAttribute("resultList") DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		//获得传过来的参数，默认是普通班
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchClassType())){
			queryCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
		}
		//默认查询当前年
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchYear())){
			Calendar a=Calendar.getInstance();  
			queryCommond.setSearchYear(a.get(Calendar.YEAR));
		}
		if (attributeConverter != null) {
			parameterValueConver(queryCommond, request, attributeConverter);
		}
		//调用service层查询分配参学名额列表的方法
		List<DeptAssignedInfoBean> result = deptAssignedInfoService.findDeptAssignedInfoList(queryCommond);
		queryCommond.setResultList(result);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("查询成功！");
		return "";
	}
	/**
	 *  导出参学名额的列表
	 * @param querycommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @createDate 2015-1-5
	 */
	@RequestMapping(value = "/exportDeptAssignedInfoList")
	public void exportDeptAssignedInfoList(
			@ModelAttribute("resultList") DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		//获得传过来的参数，默认是普通班
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchClassType())){
			queryCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
		}
		//默认查询当前年
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchYear())){
			Calendar a=Calendar.getInstance();  
			queryCommond.setSearchYear(a.get(Calendar.YEAR));
		}
		//调用service层查询分配参学名额列表的方法
		List<DeptAssignedInfoBean> result = deptAssignedInfoService.ExpertDeptAssignedInfoList(queryCommond);
		ExportDeptAssigneInfoBean edb=null;
		List<ExportDeptAssigneInfoBean> edbBeans=new ArrayList<ExportDeptAssigneInfoBean>();
		for(DeptAssignedInfoBean db :result){
			edb=new ExportDeptAssigneInfoBean();
			edb.setDeptName(db.getDeptName());
			edb.setDeptUserNum(db.getDeptUserNum().toString());
			edb.setRestrictPersonNum(db.getRestrictPersonNum().toString());
			edbBeans.add(edb);
		}
		DeptAssigneInfoExport dExport=new DeptAssigneInfoExport();
		dExport.setExportClassBean(edbBeans);
		DeptAssigneInfoSheet dSheet=new DeptAssigneInfoSheet();
		dSheet.setExportObject(dExport);
		dSheet.setExprotFormatName("deptAssigneInfoExportConfig");
		dSheet.setSheetName("分配参学名额列表");
		Sheet[] sheetArray = new Sheet[] { dSheet };// 导出Excel的Sheet集合
		ExcelIO excelio = ExcelIOFactory.getExcelIO();// Excel导出工具
		String title="分配参学名额列表";
		response.setContentType("application/msexcel;charset=ISO8859-1");
		response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");
		OutputStream out = response.getOutputStream();
		excelio.exportExcel(out, "resumeExportStyle", sheetArray, false);
	}
	/**
	 * 修改分配参学名额列表上的限定人数
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2014-12-30
	 */
	@RequestMapping(value = "/updateDeptAssignedInfo")
	public String updateDeptAssignedInfo(@ModelAttribute("result") DeptAssignedInfoValidCommond validCommond,
			HttpServletRequest request,HttpServletResponse response, 
			@ModelAttribute("resultState") ResultState resultState)throws Exception {
		//获得前端传过来的参数
		if (PropertyUtil.objectNotEmpty(validCommond.getId())&&PropertyUtil.objectNotEmpty(validCommond.getRestrictPersonNum())) {
			//调用service层更新限定人数的方法
			boolean result = deptAssignedInfoService.updateDeptAssignedInfo(validCommond);
			if (!result) {
				resultState.setState(ResultState.RESULT_STATE_FAIL);
				resultState.setMessage("更新失败！");
			}else {
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
				resultState.setMessage("更新成功！");
			}
		}else{
			resultState.setState(ResultState.RESULT_STATE_FAIL);
			resultState.setMessage("未传入要更新的记录!");
		}
		return "";
	}
	/**
	 * 分配参学名额:未选单位列表
	 * @param querycommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2014-12-30
	 */
	@RequestMapping(value = "/findNoSelectSignupDeptList")
	public String findNoSelectSignupDeptList(
			@ModelAttribute("resultList") DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		//获得传过来的参数
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchParentId())){
			if (attributeConverter != null) {
				parameterValueConver(queryCommond, request, attributeConverter);
			}
			//获得传过来的参数，默认是普通班
			if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchClassType())){
				queryCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
			}
			//查询当前年
			Calendar a=Calendar.getInstance();  
			int year=a.get(Calendar.YEAR);
			queryCommond.setSearchYear(year);
			//调用service层查询分配参学名额:未选单位列表的方法
			List<DeptAssignedInfoBean> result = deptAssignedInfoService.findNoSelectSignupDeptList(queryCommond);
			queryCommond.setResultList(result);
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("查询成功！");
		}else{
			resultState.setMessage("未选中任何单位！");
		}
		return "";
	}
	/**
	 * 添加单位年度参学名额
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2014-12-30
	 */
	@RequestMapping(value = "/addDeptAssignedInfo")
	public String addDeptAssignedInfo(@ModelAttribute("result") DeptAssignedInfoValidCommond validCommond,
			HttpServletRequest request,HttpServletResponse response, 
			@ModelAttribute("resultState") ResultState resultState)throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		//获得前端传过来的参数
		if (PropertyUtil.objectNotEmpty(validCommond.getIds())) {
			Calendar a=Calendar.getInstance();  
			int year=a.get(Calendar.YEAR);
			int restrictPersonNum=0;
			for(int i=0;i<validCommond.getIds().length;i++){
				DeptAssignedInfoValidCommond vCommond = new DeptAssignedInfoValidCommond();
				vCommond.setYear(year);//年份
				//如果是普通班:报名限额按照单位总人数的30%
				if(DeptAssignedInfo.ORDINARY_CLASS.equals(validCommond.getClassType())){
					restrictPersonNum=(validCommond.getRestrictPersonNums()[i]+1)/3;
				}
				vCommond.setRestrictPersonNum(restrictPersonNum);//限报人数
				SignupDept department=new SignupDept();
				department.setDepid(validCommond.getIds()[i]);
				vCommond.setDepartment(department);//部门
				vCommond.setClassType(validCommond.getClassType());
				deptAssignedInfoService.save(vCommond);
			}
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("添加成功!");
		}else{
			resultState.setMessage("未选中任何单位!");
		}
		return "";
	}
	/**
	 * 删除分配参学名额
	 * @param querycommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2014-12-31
	 */
	@RequestMapping(value = "/deleteDeptAssignedInfo")
	public String deleteDeptAssignedInfo(
			@ModelAttribute("resultList") DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		//获得传过来的参数
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchIds())&&PropertyUtil.objectNotEmpty(queryCommond.getSearchDepIds())){
			//获得传过来的参数，默认是普通班（包括班级表中的普通班和定向班）
			if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchClassType())){
				queryCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
				String[] searchClassTypes={TrainingClass.PTB_CLASS_TYPE,TrainingClass.DXB_CLASS_TYPE};
				queryCommond.setSearchClassTypes(searchClassTypes);
			}else{//根据传过来的培训班类型获得对应班级表中班级类型
				//普通班（包括班级表中的普通班和定向班）
				if(DeptAssignedInfo.ORDINARY_CLASS.equals(queryCommond.getSearchClassType())){
					String[] searchClassTypes={TrainingClass.PTB_CLASS_TYPE,TrainingClass.DXB_CLASS_TYPE};
					queryCommond.setSearchClassTypes(searchClassTypes);
				}
				//国防班（包括班级表中的国防班）
				if(DeptAssignedInfo.DEFENSE_CLASS.equals(queryCommond.getSearchClassType())){
					String[] searchClassTypes={TrainingClass.GFB_CLASS_TYPE};
					queryCommond.setSearchClassTypes(searchClassTypes);
				}
			}
			//查询当前年
			Calendar a=Calendar.getInstance();  
			int year=a.get(Calendar.YEAR);
			queryCommond.setSearchYear(year);
			//调用service层删除分配参学名额
			boolean result=deptAssignedInfoService.deleteDeptAssignedInfo(queryCommond);
			if (!result) {
				resultState.setMessage("已经有人参加培训班，不能删除！");
			}else {
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
				resultState.setMessage("删除成功！");
			}
		}else{
			resultState.setMessage("未选中要删除的单位!");
		}
		return "";
	}
	/**
	 * 用于排序的方法
	 * @param queryCommond
	 * @param request
	 * @param attributeConverter
	 */
	@SuppressWarnings("unchecked")
	private void parameterValueConver(DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request,
			List<IQueryCommondAttributeConverter> attributeConverter) {
		for (IQueryCommondAttributeConverter queryCommondAttributeConverter : attributeConverter) {
			queryCommondAttributeConverter.convert(queryCommond,
					request.getParameterMap());
		}
	}
	/**
	 * 查询单位年度报名情况
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @date 2014-12-29
	 */
	@RequestMapping(value = "/findDeptAssignedInfo")
	public String findDeptAssignedInfo(
			@ModelAttribute("resultList") DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		//获得登陆者的管理范围
		com.eorchis.module.security.cas.domain.Department department=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		queryCommond.setSearchDepId(department.getDeptID());
		//默认查询当前年
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchYear())){
			Calendar a=Calendar.getInstance();  
			queryCommond.setSearchYear(a.get(Calendar.YEAR));
		}
		//调用servic查询单位年度报名情况
		List<DepAssigneInfoQueryBean> result = deptAssignedInfoService.findDeptAssignedInfo(queryCommond);
		queryCommond.setResultList(result);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("查询成功！");
		return "";
	}
	
	
	/**
	 * 分配参学名额的列表分配人数汇总
	 * @param querycommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2015-01-23
	 */
	@RequestMapping(value = "/findDeptAssignedNumInfo")
	public String findDeptAssignedNumInfo(
			@ModelAttribute("resultList") DeptAssignedInfoQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState,Model model) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		//默认查询当前年
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchYear())){
			Calendar a=Calendar.getInstance();  
			queryCommond.setSearchYear(a.get(Calendar.YEAR));
		}
		//获得传过来的参数，默认是普通班
		if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchClassType())){
			queryCommond.setSearchClassType(DeptAssignedInfo.ORDINARY_CLASS);
		}
		Integer num=deptAssignedInfoService.findDeptAssignedNumInfo(queryCommond);
		PreSqSyUserBean pb=new PreSqSyUserBean();
		pb.setSqUserNum(num);
		model.addAttribute("result", pb);
		resultState.setMessage("操作成功！");
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
}
